package sdk

import (
	"cgs-server/helper"
	"cgs-server/server"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func init() {
	server.Post("/api/sdk/AddKey", AddKey, "添加APP Key", server.None)           //
	server.Get("/api/sdk/ListKey", ListKey, "List APP Key", server.None)       //
	server.Post("/api/sdk/EditKey", EditKey, "修改APP Key", server.None)         //
	server.Post("/api/sdk/RemoveKey", RemoveKey, "RemoveAPP Key", server.None) //
}

func AddKey(w http.ResponseWriter, r *http.Request) {
	user, _ := server.GetCurrentUser(r)
	if user == nil {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "Permission denied.",
		})
		return
	}
	key := primitive.NewObjectID().Hex()
	secret := helper.Encrypt(key)
	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	sign := helper.EncryptBase62(key + "&" + secret + "&" + timestamp)
	now := time.Now()
	doc := bson.M{
		"ID":         primitive.NewObjectID(),
		"AppKey":     key,
		"AppSecret":  secret,
		"Sign":       sign,
		"AuthType":   "0",
		"Timestamp":  timestamp,
		"UserID":     user.ID,
		"CreateTime": now,
		"UpdateTime": now,
	}
	db, err := server.Mongo()
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}
	db.InsertOne(server.CgsAppKeyCollectionName, doc)
	AppKey := AppKey{
		ID:        doc["ID"].(primitive.ObjectID),
		AppKey:    doc["AppKey"].(string),
		AppSecret: doc["AppSecret"].(string),
		Sign:      doc["Sign"].(string),
		AuthType:  doc["AuthType"].(string),
	}

	helper.WriteJSON(w, server.Result{
		Code: 200,
		Msg:  "Add Successfully!",
		Data: AppKey,
	})

}
func ListKey(w http.ResponseWriter, r *http.Request) {
	user, _ := server.GetCurrentUser(r)
	if user == nil {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "Permission denied.",
		})
		return
	}
	db, err := server.Mongo()
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}
	//docs := bson.A{}
	filter := bson.M{
		"UserID": user.ID,
	}
	opts := options.FindOptions{
		Sort: bson.M{
			"UpdateTime": -1,
		},
	}
	list := []AppKey{}
	db.FindMany(server.CgsAppKeyCollectionName, filter, &list, &opts)

	//for _, i := range docs {
	//	doc := i.(primitive.D).Map()
	//	remark := ""
	//	if doc["Remark"] != nil {
	//		remark = doc["Remark"].(string)
	//	}
	//	AppKey := AppKey{
	//		ID:        doc["ID"].(primitive.ObjectID),
	//		AppKey:    doc["AppKey"].(string),
	//		AppSecret: doc["AppSecret"].(string),
	//		Sign:      doc["Sign"].(string),
	//		AuthType:  doc["AuthType"].(string),
	//		Remark:    remark,
	//	}
	//	list = append(list, AppKey)
	//}
	helper.WriteJSON(w, server.Result{
		Code: 200,
		Msg:  "Get Successfully!",
		Data: list,
	})
}
func EditKey(w http.ResponseWriter, r *http.Request) {
	user, _ := server.GetCurrentUser(r)
	if user == nil {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "Permission denied.",
		})
		return
	}
	r.ParseForm()
	id, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("ID")))
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "ID is not allowed to be empty.",
		})
		return
	}
	authtype := r.FormValue("AuthType")
	remark := r.FormValue("Remark")
	whiteList := r.Form["WhiteList"]
	db, err := server.Mongo()
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}
	filter := bson.M{
		"ID": id,
	}
	doc := bson.M{}
	find, _ := db.FindOne(server.CgsAppKeyCollectionName, filter, &doc)
	now := time.Now()
	if !find {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "Can not find AppKey with ID " + id.String(),
		})
		return
	} else {
		// save other people's scene
		if doc["UserID"] != nil && doc["UserID"].(string) != user.ID {
			helper.WriteJSON(w, server.Result{
				Code: 300,
				Msg:  "Permission denied.",
			})
			return
		}

		set := bson.M{
			"UpdateTime": now,
		}
		if authtype != "" {
			set["AuthType"] = authtype
		}
		if remark != "" {
			set["Remark"] = remark
		}
		if whiteList == nil {
			whiteList = []string{}
		}
		set["WhiteList"] = whiteList
		update := bson.M{
			"$set": set,
		}
		db.UpdateOne(server.CgsAppKeyCollectionName, filter, update)

	}
	helper.WriteJSON(w, server.Result{
		Code: 200,
		Msg:  "Update successfully!",
	})

}
func RemoveKey(w http.ResponseWriter, r *http.Request) {
	user, _ := server.GetCurrentUser(r)
	if user == nil {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "Permission denied.",
		})
		return
	}
	r.ParseForm()
	id, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("ID")))
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "ID is not allowed to be empty.",
		})
		return
	}
	db, err := server.Mongo()
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}
	filter := bson.M{
		"ID":     id,
		"UserID": user.ID,
	}
	db.DeleteOne(server.CgsAppKeyCollectionName, filter)
	helper.WriteJSON(w, server.Result{
		Code: 200,
		Msg:  "Delete successfully!",
	})
}
